package com.hh.usercenter.controller;

import com.google.gson.Gson;
import com.hh.commonutils.jwt.JwtUtil;
import com.hh.usercenter.entity.UcenterMember;
import com.hh.usercenter.service.UcenterMemberService;
import com.hh.usercenter.utils.ConstantWxValue;
import com.hh.usercenter.utils.HttpClientUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;

@Controller

@RequestMapping("/api/ucenter/wx")
public class WxController {
    @Autowired
    private UcenterMemberService ucenterMemberService;

    // 获取微信登录的二维码
    @GetMapping("/getWxCode")
    public String getWxCode(){
        // %s 相当于占位符
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect?" +
                "appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";

        String redirectUrl = ConstantWxValue.REDURECT_URL;
        try {
            redirectUrl = ConstantWxValue.REDURECT_URL = URLEncoder.encode(redirectUrl, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        String format = String.format(baseUrl,
                ConstantWxValue.APP_ID,
                redirectUrl,
                "atguigu");
        return "redirect:"+format;
    }

    // 扫描登陆后的回调函数
    @GetMapping("/callback")
    public String getToken(String code,String state){
        String baseUrl = "https://api.weixin.qq.com/sns/oauth2/access_token"+
                            "?appid=%s" +
                            "&secret=%s" +
                            "&code=%s" +
                            "&grant_type=authorization_code";
        baseUrl = String.format(baseUrl, ConstantWxValue.APP_ID, ConstantWxValue.APP_SECRET, code);

        // 使用httpClient发起请求，获取带有access_token和openid的token
        String accessTokenUrl = null;
        try {
            accessTokenUrl = HttpClientUtils.get(baseUrl,"utf-8");
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("获取Token失败!");
        }

        // 把返回的带access_token及oppenid的链接转为HashMap，以提取数据
        Gson gson = new Gson();
        HashMap accessTokenMap = gson.fromJson(accessTokenUrl, HashMap.class);

        String access_token = (String) accessTokenMap.get("access_token");
        String openid = (String) accessTokenMap.get("openid");

        // 去数据库查询看是否登陆过
        UcenterMember ucenterMember = ucenterMemberService.getInfoByOpenId(openid);

        if (null == ucenterMember) {
            String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                    "?access_token=%s" +
                    "&openid=%s";
            baseUserInfoUrl = String.format(baseUserInfoUrl, access_token, openid);

            // 使用格式化后的url发起HttpClient请求，获取用户信息
            String userInfo = null;
            try {
                userInfo = HttpClientUtils.get(baseUserInfoUrl,"utf-8");
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException("获取用户信息失败!");
            }

            HashMap userInfoMap = gson.fromJson(userInfo, HashMap.class);

            String nickname = (String) userInfoMap.get("nickname");
            String headImgUrl = (String) userInfoMap.get("headimgurl");

            ucenterMember = new UcenterMember();
            ucenterMember.setOpenid(openid);
            ucenterMember.setNickname(nickname);
            ucenterMember.setAvatar(headImgUrl);
            ucenterMemberService.save(ucenterMember);
        }

        String token = JwtUtil.getJwtToken(ucenterMember.getId(), ucenterMember.getNickname());
        return "redirect:http://192.168.60.120:3000?token=" + token;
    }
}
